package com.hyt.it.ogt.ks.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.common.utils.result.Result;
import com.hyt.it.ogt.ks.config.ConfigManager;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.feign.KwClient;
import com.hyt.it.ogt.ks.feign.TpsClient;
import com.hyt.it.ogt.ks.model.entity.CandidateProcess;
import com.hyt.it.ogt.ks.model.vo.BucketVO;
import com.hyt.it.ogt.ks.model.vo.UploadPhotoVO;
import com.hyt.it.ogt.ks.model.vo.monitor.request.CandidatePhotoVO;
import com.hyt.it.ogt.ks.service.ICandidateProcessService;
import com.hyt.it.ogt.ks.service.ILogService;
import com.hyt.it.ogt.ks.util.Constants;
import com.hyt.model.tps.vo.Bucket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * userid即examcandidateid
 * @author 刘恒活
 * @since 2020/8/24 10:12
 */
@RestController
@RequestMapping("/ks/bucket")
@Api(tags = "12.云存储", value = "云存储")
@ApiSort(12)
@Slf4j
public class BucketController {
    public static final String DIR = "tmp";
    @Resource
    private ConfigManager configManager;
    @Resource
    private TpsClient tpsClient;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private KwClient kwClient;
    @Resource
    private ICandidateProcessService iCandidateProcessService;
    @Resource
    private ILogService iLogService;

    @ApiOperation(value = "12.1 获取腾讯云存储临时凭证", response = BucketVO.class)
    @ApiOperationSort(1)
    @GetMapping("getBucketTempCredential")
    public ApiResponse<BucketVO> getBucketTempCredential(@RequestParam String examId,
                                                         @RequestParam(required = false) String admissionNumber) {
        BucketVO res = new BucketVO();
        try {
            Long start = System.currentTimeMillis();
            String json = tpsClient.getBucketTempCredential("0");
            log.info("获取bucket临时凭证:{}", json);
            Long end = System.currentTimeMillis();
            log.info("===获取bucket临时凭证 getBucketTempCredential 调用tps服务返回数据用时:{} 秒",(end - start) / 1000);
            Result result = JSON.parseObject(json, Result.class);
            if(result.getObj() != null) {
                Bucket bucket = JSON.parseObject(result.getObj().toString(), Bucket.class);
                BeanUtils.copyProperties(bucket, res);
                if(StringUtils.isBlank(admissionNumber)) {
                    // 腾讯云
                    res.setPath(StringUtils.join(configManager.getPhotoBucketPath(), examId,
                            Constants.HTTP_SEP, DIR, Constants.HTTP_SEP));
                } else {
                    // 腾讯云
                    res.setPath(StringUtils.join(configManager.getPhotoBucketPath(), examId,
                            Constants.HTTP_SEP, admissionNumber, Constants.HTTP_SEP));
                }
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return ApiResponse.<BucketVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(res).build();
    }

    @ApiOperation(value = "12.2 保存图片信息", response = UploadPhotoVO.class)
    @ApiOperationSort(2)
    @PostMapping("savePhotoBucketInfo")
    public ApiResponse<Object> savePhotoBucketInfo(@RequestBody CandidatePhotoVO vo) {
        log.info("# 保存图片信息：{}", vo);
        UploadPhotoVO uploadPhoto = new UploadPhotoVO();
        try {
            Long start = System.currentTimeMillis();
            String photoUrl = URLDecoder.decode(vo.getImageURL());
            kwClient.saveCandidatePhoto(vo.getExamCandidateId(), photoUrl, vo.getPhotoFrom(), vo.getPhotoType());
            Long second = System.currentTimeMillis();
            log.info("====savePhotoBucketInfo====,第一步调用kw保存照片信息用时:{}秒",(second - start) / 1000);
            boolean updateCandidateProcess = false;
            uploadPhoto.setStatus(vo.getAuthentication());
            // 是否需要人脸核身（0:不需要，1:需要）
            if(vo.getAuthentication() == 0) {
                String jsonFaceDetect = kwClient.faceDetectByUrl(vo.getExamId(), vo.getExamCandidateId(), photoUrl);
                Long third = System.currentTimeMillis();
                log.info("请求考务人脸识别接口kwClient.faceDetectByUrl返回数据{}", jsonFaceDetect);
                log.info("====savePhotoBucketInfo====,第二步请求考务人脸识别接口kwClient.faceDetectByUrl用时:{}秒",(third - start) / 1000);
                ApiResponse<Integer> resJsonFaceDetect = ApiResponse.ConvertRet(jsonFaceDetect, Integer.class);
                uploadPhoto.setPersonCount(resJsonFaceDetect.getData());
                updateCandidateProcess = true;
            } else {
                Boolean enabled = configManager.getEnabled().equals("true") ? true : false;
                String candidates = configManager.getCandidateIds();
                Boolean configEnabled = enabled && candidates.contains(vo.getExamCandidateId());
                Boolean redisEnabled =
                        redisTemplate.opsForValue().get("CANCEL_FACE_VALID:" + vo.getExamCandidateId()) != null;
                if(configEnabled || redisEnabled) {
                    log.info("港澳台考生{}跳过人脸比对", vo.getExamCandidateId());
                    uploadPhoto.setFaceCompareResult(1);
                    updateCandidateProcess = true;
                } else {
                    String bm = kwClient.faceDetectEnrollPhotoByUrl(vo.getExamId(), vo.getExamCandidateId(), photoUrl);
                    ApiResponse<Integer> resJson = ApiResponse.ConvertRet(bm, Integer.class);
                    Long third = System.currentTimeMillis();
                    log.info("请求考务人脸识别接口kwClient.faceDetectEnrollPhotoByUrl返回数据{}", resJson);
                    log.info("====savePhotoBucketInfo====,第二步(港澳台)请求考务人脸识别接口kwClient.faceDetectByUrl用时:{}秒",(third - start) / 1000);
                    uploadPhoto.setFaceCompareResult(resJson.getData());
                    if (resJson.getCode() == BizStatusCode.KW_SUCCESS_OK.getCode().intValue()
                            && resJson.getData() == 1) {
                        updateCandidateProcess = true;
                    }
                }
            }
            if(vo.getPhotoType() == 1 && updateCandidateProcess){
                LambdaQueryWrapper<CandidateProcess> query = Wrappers.lambdaQuery();
                query.eq(CandidateProcess::getCandidateId, vo.getExamCandidateId());
                query.eq(CandidateProcess::getExamId,vo.getExamId());
                CandidateProcess entity = new CandidateProcess();
                entity.setTakePicture(true);
                iCandidateProcessService.update(entity, query);
                Long fouth = System.currentTimeMillis();
                log.info("====savePhotoBucketInfo====,第三步更新考生过程表 用时:{}秒",(fouth - start) / 1000);
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return ApiResponse.builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(uploadPhoto).build();
    }

    @ApiOperation(value = "12.3 获取华为云存储临时凭证", response = Bucket.class)
    @ApiOperationSort(3)
    @GetMapping("getHwObsCredential")
    public ApiResponse<Bucket> getHwObsTempCredential(@RequestParam String examId,
                                                        @RequestParam(required = false) String admissionNumber) {
        try {
            ApiResponse<Bucket> hwObsTempCredential = tpsClient.getHwObsCredential("0");
            return ApiResponse.<Bucket>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode())
                    .data(hwObsTempCredential.getData()).build();
        } catch (Exception e) {
            log.error("", e);
            return ApiResponse.<Bucket>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).build();
        }
    }

    @ApiOperation(value = "12.4 获取腾讯云存储临时凭证-客户端截屏", response = BucketVO.class)
    @ApiOperationSort(4)
    @GetMapping("getBucketTempCredentialScreenShot")
    public ApiResponse<BucketVO> getBucketTempCredentialScreenShot(@RequestParam String examId,
                                                         @RequestParam(required = false) String admissionNumber) {
        BucketVO res = new BucketVO();
        try {
            Long start = System.currentTimeMillis();
            String json = tpsClient.getBucketTempCredential("0");
            log.info("获取bucket临时凭证:{}", json);
            Long end = System.currentTimeMillis();
            log.info("===获取bucket临时凭证 getBucketTempCredential 调用tps服务返回数据用时:{} 秒",(end - start) / 1000);
            Result result = JSON.parseObject(json, Result.class);
            if(result.getObj() != null) {
                Bucket bucket = JSON.parseObject(result.getObj().toString(), Bucket.class);
                BeanUtils.copyProperties(bucket, res);
                if(StringUtils.isBlank(admissionNumber)) {
                    // 腾讯云
                    res.setPath(StringUtils.join(configManager.getScreenshotPath(), examId,
                            Constants.HTTP_SEP, DIR, Constants.HTTP_SEP));
                } else {
                    // 腾讯云
                    res.setPath(StringUtils.join(configManager.getScreenshotPath(), examId,
                            Constants.HTTP_SEP, admissionNumber, Constants.HTTP_SEP));
                }
                String examCandidateId = iCandidateProcessService.getExamCandidateByAdmissionNumber(examId, admissionNumber);
                iLogService.screenShotLog(examId, Objects.nonNull(examCandidateId) ? examCandidateId : admissionNumber);

            }
        } catch (Exception e) {
            log.error("", e);
        }
        return ApiResponse.<BucketVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(res).build();
    }

}
